import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { API_CONFIG } from '../config/apiConfig';
import { useKnowledgeBaseStore } from './knowledgebaseStore';

export interface TransferTask {
  id: string;
  fileName: string;
  baseId: string;
  status: 'uploading' | 'indexing' | 'completed' | 'failed';
  progress: number;
  error?: string;
  createdAt: Date;
}

export const useTransferStore = defineStore('transfer', () => {
  const tasks = ref<TransferTask[]>([]);
  const isMinimized = ref(false);
  const showTransferList = ref(false);
  
  // 计算属性：活跃任务数量
  const activeTasksCount = computed(() => {
    return tasks.value.filter(task => task.status === 'uploading' || task.status === 'indexing').length;
  });
  
  // 计算属性：已完成任务数量
  const completedTasksCount = computed(() => {
    return tasks.value.filter(task => task.status === 'completed').length;
  });
  
  // 计算属性：失败任务数量
  const failedTasksCount = computed(() => {
    return tasks.value.filter(task => task.status === 'failed').length;
  });
  
  // 添加新任务
  const addTask = (taskId: string, fileName: string, baseId: string) => {
    const newTask: TransferTask = {
      id: taskId,
      fileName,
      baseId,
      status: 'uploading',
      progress: 0,
      createdAt: new Date()
    };
    
    tasks.value.push(newTask);
    showTransferList.value = true;
    
    // 开始轮询任务状态
    pollTaskStatus(taskId, baseId);
    
    return newTask;
  };
  
  // 更新任务状态
  const updateTaskStatus = (taskId: string, status: TransferTask['status'], progress: number, error?: string) => {
    const task = tasks.value.find(t => t.id === taskId);
    if (task) {
      task.status = status;
      task.progress = progress;
      if (error) {
        task.error = error;
      }
    }
  };
  
  // 更新任务进度
  const updateTaskProgress = (taskId: string, progress: number) => {
    const task = tasks.value.find(t => t.id === taskId);
    if (task) {
      task.progress = progress;
    }
  };
  
  // 标记任务为完成
  const completeTask = (taskId: string) => {
    updateTaskStatus(taskId, 'completed', 100);
  };
  
  // 标记任务为失败
  const failTask = (taskId: string, error?: string) => {
    updateTaskStatus(taskId, 'failed', 0, error || '上传失败');
  };
  
  // 轮询任务状态
  const pollTaskStatus = async (taskId: string, baseId: string) => {
    const knowledgebaseStore = useKnowledgeBaseStore();
    let retryCount = 0;
    const maxRetries = 3;
    
    const checkStatus = async () => {
      try {
        const response = await fetch(`${API_CONFIG.BASE_URL}/knowledge-base/task/${taskId}/task-status`, {
          method: 'GET',
          credentials: 'include'
        });
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const result = await response.json();
        if (result.code === '0') {
          const status = result.data;
          
          // 根据不同的状态更新任务进度和状态
          switch(status) {
            case 'CONTENT_ANALYSIS':
              updateTaskStatus(taskId, 'uploading', 30);
              setTimeout(checkStatus, 2000);
              break;
            case 'INDEXING_VECTORIZATION':
              updateTaskStatus(taskId, 'indexing', 70);
              setTimeout(checkStatus, 2000);
              break;
            case 'DONE':
              // 任务完成，更新状态并停止轮询
              updateTaskStatus(taskId, 'completed', 100);
              // 刷新文件列表
              if (baseId) {
                await knowledgebaseStore.fetchFolderFiles(baseId, true);
              }
              return;
            case 'ERROR':
              // 任务失败，更新状态并停止轮询
              updateTaskStatus(taskId, 'failed', 0, '上传失败');
              return;
            default:
              // 其他未知状态，继续轮询
              setTimeout(checkStatus, 2000);
          }
        } else {
          // API返回错误
          retryCount++;
          if (retryCount <= maxRetries) {
            setTimeout(checkStatus, 3000);
          } else {
            updateTaskStatus(taskId, 'failed', 0, result.msg || '状态检查失败');
            return;
          }
        }
      } catch (error) {
        console.error('检查任务状态失败:', error);
        retryCount++;
        if (retryCount <= maxRetries) {
          setTimeout(checkStatus, 3000);
        } else {
          updateTaskStatus(taskId, 'failed', 0, '网络错误');
          return;
        }
      }
    };
    
    // 开始检查
    setTimeout(checkStatus, 1000);
  };
  
  // 清除已完成任务
  const clearCompletedTasks = () => {
    tasks.value = tasks.value.filter(task => 
      task.status !== 'completed' && task.status !== 'failed'
    );
  };
  
  // 切换最小化状态
  const toggleMinimize = () => {
    isMinimized.value = !isMinimized.value;
  };
  
  // 切换显示状态
  const toggleShow = () => {
    showTransferList.value = !showTransferList.value;
  };
  
  return {
    tasks,
    isMinimized,
    showTransferList,
    activeTasksCount,
    completedTasksCount,
    failedTasksCount,
    addTask,
    updateTaskStatus,
    updateTaskProgress,
    completeTask,
    failTask,
    clearCompletedTasks,
    toggleMinimize,
    toggleShow
  };
});